<template>
  <p-modal
    :visible="visible"
    :title="title"
    :mask-closable="false"
    :destroy-on-close="true"
    :width="600"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <p-table
      :row-key="(record, index) => index"
      :custom-header-row="customHeaderRowMinxin"
      :pagination="false"
      :columns="columns"
      :data-source="formatData"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChanges,
      }"
      bordered
    >
      <template slot="handleUserName" slot-scope="text">
        <div class="item-container">
          <p-icon type="user" style="margin-right: 8px" />
          <span>{{ text || '-' }}</span>
        </div>
      </template>
    </p-table>
    <p-form-model
      ref="form"
      style="margin-top: 15px"
      :label-col="{ span: 2 }"
      :wrapper-col="{ span: 22 }"
      :model="form"
      :rules="rules"
    >
      <p-form-model-item label="原因:" prop="reason">
        <p-textarea
          v-model="form.reason"
          placeholder="请输入"
          style="height: 80px; resize: none"
        />
      </p-form-model-item>
    </p-form-model>
  </p-modal>
</template>

<script>
import { postReuseDetail } from '@/api/price';
import { getUserInfo } from '@/api/public';
import mixinTable from '@/mixins/mixin-table.js';
const defaultForm = {
  name: [],
  reason: '',
};
export default {
  mixins: [mixinTable],
  props: {
    title: {
      type: String,
      default: '转他人处理',
    },
    number: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [String, Number],
      default: undefined,
    },
    detail: {
      type: Object,
      default: () => ({}),
    },
    selected: {
      type: Array,
      default: () => [],
    },
    selecteds: {
      type: Object,
      default: () => ({}),
    },
    planId: {
      type: [String, Number],
      default: undefined,
    },
  },

  data() {
    return {
      selectedRowKeys: [],
      formatData: [],
      form: {
        ...defaultForm,
      },
      rules: {
        name: [
          { required: true, message: '请输入或选择处理人！', trigger: 'blur' },
        ],
        reason: [{ max: 256, message: '输入的内容过长', trigger: 'blur' }],
      },
      fetching: false,
    };
  },
  computed: {
    columns() {
      return [
        {
          align: 'center',
          title: '序号',
          width: 50,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: this.number,
          dataIndex: 'serialNumber',
          width: 120,
        },
        {
          align: 'center',
          title: '当前处理人名称',
          dataIndex: 'handleUserName',
          width: 120,
          scopedSlots: { customRender: 'handleUserName' },
        },
        {
          align: 'center',
          title: '处理人',
          required: true,
          dataIndex: 'name',
          customRender: (value, row, index) => {
            const children = (
              <SelectSearchPeople
                value={value}
                label-in-value={true}
                vOn:select={(e) => this.handleSelect(e, row, 'name')}
                vOn:deselect={(e) => this.handleDeselect(e, row, 'name')}
              />
            );

            return this.customRender(children, index);
          },
        },
      ];
    },
  },
  watch: {
    visible: {
      async handler(val) {
        if (!val) return;
        this.selectedRowKeys = [];
        console.log(this.selecteds, '0000000000');
        this.formatData = this.selecteds;
      },
      immediate: true,
    },
  },
  methods: {
    handleSelect(e, row, key) {
      console.log('e, row, key: ', e, row, key);
      row[key] = [e];
    },
    handleDeselect(e, row, key) {
      console.log('e, row, key: ', e, row, key);
      row[key] = [];
    },
    customRender(children, index, key) {
      return {
        children,
      };
    },
    handleInputChange(e, text, record, index, key) {
      console.log('text, record, index: ', e, text, record, index);
      record[key] = e;
    },
    onSelectChanges(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    handleCancel() {
      this.formatData = [];
      this.form = { ...defaultForm };
      this.list = [];
      this.$emit('update:visible', false);
    },
    handleOk() {
      if (!this.selectedRowKeys.length) {
        this.$message.error('请勾选至少一条转他人处理信息');
        return;
      }
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          console.log('this.formatData: ', this.formatData);

          const list = this.formatData.map((item) => {
            return {
              id: item.planId,
              userName:
                item.name[0]?.label.indexOf('-') === -1
                  ? item.name[0].label
                  : item.name[0].label.split('-')[0],
              // userName: item.name[0].label,
              userId: item.name[0].key,
              remark: this.form.reason,
              currentUserName: item.handleUserName,
              currentUserId: item.currentUserId,
            };
          });
          let params = [];
          this.selectedRowKeys.forEach((item) => {
            params.push(list[item]);
          });
          console.log('params: ', params);
          const isValid = params.every((item) => item.userId);
          console.log('noValid: ', isValid);
          if (!isValid) {
            this.$message.error('勾选的处理人不能为空');
            return;
          }

          await postReuseDetail(params);
          this.$message.success('转办成功');
          this.$emit('change', this.form);
          this.$emit('fresh');
          this.formatData = [];
          this.handleCancel();
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .poros-form-item {
  margin-bottom: 0;
}
.item-container {
  display: flex;
  align-items: center;
}
</style>